package com.hexiang.servlet;

import com.hexiang.task.AsyncTask;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.AsyncContext;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.ThreadPoolExecutor;

@WebServlet(urlPatterns = "/nonBlockAsyncServlet", asyncSupported = true)
@Slf4j
public class NonBlockingAsyncServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException {
        long startTime = System.currentTimeMillis();
        log.info("NonBlockingAsyncServletStart");
        AsyncContext asyncCtx = httpServletRequest.startAsync();
        String time = httpServletRequest.getParameter("time");
        int secs = StringUtils.isNotBlank(time) ? Integer.parseInt(time) : 2000;

        ThreadPoolExecutor executor = (ThreadPoolExecutor) httpServletRequest
                .getServletContext().getAttribute("executor");
        ServletInputStream inputStream = httpServletRequest.getInputStream();

        inputStream.setReadListener(new ReadListener() {
            @Override
            public void onDataAvailable() {
            }

            @Override
            public void onAllDataRead() {
                log.info("onAllDataRead");
                executor.execute(new AsyncTask(asyncCtx, secs));
            }

            @Override
            public void onError(Throwable t) {
                log.error("onError", t);
                asyncCtx.complete();
            }
        });
        long endTime = System.currentTimeMillis();
        log.info("NonBlockingAsyncServletEnd,time cost {} ms.", endTime - startTime);

    }
}